package com.daltonsoft.daxc;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

import com.daltonsoft.xmpp.Node;
import com.daltonsoft.xmpp.TagNames;
import com.daltonsoft.xmpp.XmppClient;
import com.daltonsoft.xmpp.client.ShowStanza;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class HomeActivity extends Activity implements
		AdapterView.OnItemClickListener, Callable<ArrayAdapter<String>> {

	ListView rosterListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		rosterListView = (ListView) findViewById(R.id.rosterListView);
		rosterListView.setOnItemClickListener(this);
		try {
			ArrayAdapter<String> adapter = Executors.newSingleThreadExecutor()
					.submit(this).get();
			rosterListView.setAdapter(adapter);
		} catch (Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_home, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public ArrayAdapter<String> call() throws Exception {
		XmppClient x = DAXCApp.getInstance().xmppClient;
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1);
		Node[] r = x.getRoster().getChildren(TagNames.QUERY)[0]
				.getChildren(TagNames.ITEM);
		for (Node c : r)
			adapter.add(c.getAttributeValue("name") + "\n"
					+ c.getAttributeValue("jid"));
		x.setPresence(ShowStanza.Text.CHAT, "Available");
		return adapter;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent = new Intent(this, MessageActivity.class);
		intent.putExtra("Email", ((TextView) view).getText());
		startActivity(intent);
	}
}
